package org.wu.framework.log.platform.filter;

import cn.hutool.http.Header;
import cn.hutool.http.useragent.OS;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;
import org.wu.framework.log.platform.application.RequestLogApplication;
import org.wu.framework.log.platform.application.command.request.log.RequestLogStoryCommand;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Configuration
public class LazyInterceptorLogFilter extends OncePerRequestFilter {


    private final RequestLogApplication requestLogApplication;

    private final String ACCESS_REQUEST_ID = "Access-Request-Id";

    public LazyInterceptorLogFilter(RequestLogApplication requestLogApplication) {
        this.requestLogApplication = requestLogApplication;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("log");
        String requestId = request.getHeader(ACCESS_REQUEST_ID);
        requestId = Objects.isNull(requestId) ? UUID.randomUUID().toString() : requestId;
        String requestURI = request.getRequestURI();
        String method = request.getMethod();


        String ipAddr = getIpAddr(request);

        String remoteAddr = request.getRemoteAddr();
        log.info("remoteAddr:{}", remoteAddr);
        Object userId = request.getAttribute("ACCESS_TOKEN_USER_ID");
        if (userId == null) {
            userId = "";
        }
        RequestLogStoryCommand requestLogStoryCommand = new RequestLogStoryCommand();
        requestLogStoryCommand.setIp(ipAddr);
        requestLogStoryCommand.setRequestMethod(method);
        requestLogStoryCommand.setRequestUrl(requestURI);
//        requestLogStoryCommand.setRequestParameters();
        requestLogStoryCommand.setUserId(userId.toString());
        requestLogStoryCommand.setRequestId(requestId);
        requestLogStoryCommand.setCreateTime(LocalDateTime.now());
        requestLogStoryCommand.setSuccess(true);

        UserAgent ua = UserAgentUtil.parse(request.getHeader(Header.USER_AGENT.toString()));
        OS os = ua.getOs();
        requestLogStoryCommand.setOs(ua.getPlatform().toString() + "-" + os.getName());
        requestLogStoryCommand.setUserAgent(request.getHeader(Header.USER_AGENT.toString()));

        response.setHeader(ACCESS_REQUEST_ID, requestId);
        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            requestLogStoryCommand.setSuccess(false);
            e.printStackTrace();
        } finally {
            requestLogApplication.story(requestLogStoryCommand);
        }
    }

    public static String getIpAddr(HttpServletRequest request) {

        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }
}
